package com.kefu.call.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kefu.call.model.CallDialplan;
import com.kefu.call.model.CallDialplanApp;
import com.kefu.call.service.CallDialplanAppService;
import com.kefu.call.service.CallDialplanService;
import com.kefu.call.http.CtiClient;
import com.kefu.common.exception.BusinessException;
import com.kefu.common.mybatis.Order;
import com.kefu.sys.service.SysTenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kefu.common.controller.AbstractBaseController;
import com.kefu.common.result.Result;
import com.kefu.common.result.ResultGenerator;
import com.kefu.common.vo.DeleteVo;
import com.kefu.common.vo.DetailVo;
import com.kefu.call.model.CallInnumber;
import com.kefu.call.service.CallInnumberService;
import com.kefu.call.vo.CallInnumberSearchVo;
import com.kefu.call.vo.CallInnumberInsertVo;
import com.kefu.call.vo.CallInnumberUpdateVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.Optional;

@Api(tags = "呼入号码")
@RestController
@RequestMapping("call/innumber")
public class CallInnumberController extends AbstractBaseController {

    @Autowired
    private CallInnumberService callInnumberService;
    @Autowired
    CallDialplanService callDialplanService;
    @Autowired
    CallDialplanAppService callDialplanAppService;
    @Autowired
    CtiClient ctiClient;
    @Autowired
    SysTenantService sysTenantService;

    @PostMapping("/add")
    @ApiOperation(value = "新增呼入号码", notes = "新增呼入号码")
    public Result<String> add(@Validated @RequestBody CallInnumberInsertVo callInnumberVo) {
        logger.info("新增呼入号码:{}", callInnumberVo);

        if (callInnumberService.count(Wrappers.lambdaQuery(CallInnumber.class)
                .eq(CallInnumber::getCallnumber, callInnumberVo.getCallnumber())) > 0) {
            throw new BusinessException("号码已经存在");
        }

        CallInnumber info = callInnumberVo.convert();
        callInnumberService.save(info);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/delete")
    @ApiOperation(value = "删除呼入号码", notes = "删除呼入号码")
    public Result<String> delete(@Validated @RequestBody DeleteVo delete) {
        logger.info("删除呼入号码:{}", delete);

        CallInnumber db = callInnumberService.getById(delete.getId());
        if(StrUtil.isNotBlank(db.getCompany())){
            throw new BusinessException("请先解绑公司");
        }
        CallDialplan dialplan = callDialplanService.getOne(Wrappers.lambdaQuery(CallDialplan.class).eq(CallDialplan::getExpression, db.getCallnumber()));
        if (dialplan != null) {
            callDialplanService.deleteById(dialplan.getFOid());
            callDialplanAppService.delete(Wrappers.lambdaQuery(CallDialplanApp.class).eq(CallDialplanApp::getDialplan, dialplan.getFOid()));
        }
        callInnumberService.deleteById(delete.getId());
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/update")
    @ApiOperation(value = "修改呼入号码", notes = "修改呼入号码，绑定企业传公司id，解绑公司id传空串")
    public Result<String> update(@Validated @RequestBody CallInnumberUpdateVo vo) {
        logger.info("修改呼入号码:{}", vo);
        CallInnumber db = callInnumberService.getById(vo.getUuid());
        String company = vo.getCompany();
        //绑定企业
        if (StrUtil.isBlank(db.getCompany()) && StrUtil.isNotBlank(company)) {
            //call_dialplan
            if (callDialplanService.count(Wrappers.lambdaQuery(CallDialplan.class).eq(CallDialplan::getExpression, db.getCallnumber())) == 0) {
                String dialplanId = IdWorker.getIdStr();
                callDialplanService.save(CallDialplan.builder().fOid(dialplanId).expression(db.getCallnumber()).build());
                //call_dialplan_app
                callDialplanAppService.save(CallDialplanApp.builder().dialplan(dialplanId).data("ivr.lua " + company).application("Lua").sort(1).build());
                callDialplanAppService.save(CallDialplanApp.builder().dialplan(dialplanId).data("next.lua").application("Lua").sort(2).build());
            }
        }
        //解绑企业
        if("".equals(company)){
            CallDialplan dialplan = callDialplanService.getOne(Wrappers.lambdaQuery(CallDialplan.class).eq(CallDialplan::getExpression, db.getCallnumber()));
            if (dialplan != null) {
                callDialplanService.deleteById(dialplan.getFOid());
                callDialplanAppService.delete(Wrappers.lambdaQuery(CallDialplanApp.class).eq(CallDialplanApp::getDialplan, dialplan.getFOid()));
            }
        }
        CallInnumber info = vo.convert();
        callInnumberService.update(info);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/detail")
    @ApiOperation(value = "呼入号码详情", notes = "呼入号码详情")
    public Result<CallInnumber> detail(@Validated @RequestBody DetailVo detail) {

        CallInnumber callInnumber = callInnumberService.findById(detail.getId());
        return ResultGenerator.genSuccessResult(callInnumber);
    }

    @PostMapping("/list")
    @ApiOperation(value = "查询呼入号码", notes = "查询呼入号码")
    public Result<Page<CallInnumber>> list(@Validated @RequestBody CallInnumberSearchVo search) {

        search.setOrderField("uuid");
        search.setOrder(Order.DESC);
        Page<CallInnumber> page = callInnumberService.searchLambdaPage(search);
        page.getRecords().forEach(item -> Optional.ofNullable(item.getCompany()).map(i -> sysTenantService.getById(i)).ifPresent(i -> item.setCompanyName(i.getTenantName())));
        return ResultGenerator.genSuccessResult(page);
    }

    @PostMapping("/reloadFsConf")
    @ApiOperation(value = "刷新缓存")
    public Result<String> reloadFsConf() {
        logger.info("刷新呼叫redis数据");

        ctiClient.reloadFsConf("dialplan");
        return ResultGenerator.genSuccessResult();
    }

}
